package cn.zyjblogs.starter.oauth.interceptor;

import cn.zyjblogs.starter.common.entity.constant.HttpHeaderConstant;
import cn.zyjblogs.starter.common.entity.context.BaseContext;
import cn.zyjblogs.starter.common.entity.dto.ContextDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhuyijun
 */
@Slf4j
public class JwtTokenHandlerInterceptor extends HandlerInterceptorAdapter {

    private final boolean checkInner;

    public JwtTokenHandlerInterceptor(boolean checkInner) {
        this.checkInner = checkInner;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader(HttpHeaderConstant.AUTHORIZATION);
        if (!checkInner) {
            return true;
        }
        //token为空直接放行
        if (StringUtils.isEmpty(authorization)) {
            BaseContext.set(ContextDto.builder().build());
            return true;
        }
        return super.preHandle(request, response, handler);
    }
}
